<script setup lang="ts">
import { addAclUserAPI, delAllUserAPI, delUserAPI, getAclUserAPI, getRoleAPI, setRoleAPI, updateUserAPI } from '@/apis/acl';
import { useLayoutStore } from '@/stores/modules/setting';
import { AclUser, AllRole, AllRoleRes, records, setRoleParmas } from '@/types/acl';
import dayjs from 'dayjs';
import { onMounted, ref } from 'vue'

const page = ref(1)
const limit = ref(5)
const userList = ref<records>([])
const total = ref(0)
const drawer = ref(false)
const form = ref()
const keyword=ref('')
const roleDrawer=ref(false)

//搜索
const search=()=>{
    getAclUserData()
    keyword.value=''
}
//重置
const layoutStore=useLayoutStore()
const reset=()=>{
    layoutStore.refresh=!layoutStore.refresh
}

//获取用户列表
const getAclUserData = async () => {
    const res = await getAclUserAPI(page.value, limit.value,keyword.value)
    userList.value = res.data.records
    total.value = res.data.total
}
onMounted(() => {
    getAclUserData()
})
//改变当前页
const changeCurrent = (currentPage: number) => {
    page.value = currentPage
    getAclUserData()
}
//改变当前页码大小
const changePageSize = (pageSize: number) => {
    limit.value = pageSize
    getAclUserData()
    page.value = 1
}
//定义表单数据
const userForm = ref<AclUser>({
    username: '',
    name: '',
    password: '',
    createTime: dayjs(new Date()).format('YYYY-MM-DD hh:mm:ss'),
    updateTime: dayjs(new Date()).format('YYYY-MM-DD hh:mm:ss'),
    roleName: '',
    phone: null,
})
//定义规则
// 校验规则
const checkPassword = (_rule: any, value: any, callback: any) => {
    if (value.length >= 6) {
        callback()
    } else {
        callback(new Error('用户密码大于或等于6位'))
    }
}
const rules = {
    username: [
        { required: true, min: 2, message: '用户姓名至少大于2位', trigger: "blur" },
    ],
    name: [
        { required: true, min: 2, message: '用户昵称至少大于2位', trigger: "blur" },
    ],
    password: [
        { required: true, message: '用户密码不能为空', trigger: "blur" },
        { validator: checkPassword, trigger: 'blur' }
    ]
}

//添加用户
const addUser = () => {
    drawer.value = true
    userForm.value.id = undefined
    userForm.value.name = ''
    userForm.value.username = ''
    userForm.value.password = ''
}

//编辑用户
const updateUser = (row: any) => {
    drawer.value = true
    Object.assign(userForm.value, row)
}

// 删除用户
const onConfirm = async (id: any) => {
    await delUserAPI(id)
    if(userList.value.length > 1){
        ElMessage.success('删除成功')
        getAclUserData()
    }else{
        page.value - 1
        ElMessage.success('删除成功')
        getAclUserData()
    }
}
//取消按钮
const cancel = () => {
    form.value.resetFields()
    drawer.value = false
}

//确认按钮
const confirm = async () => {
    await form.value.validate()
    if (userForm.value.id) {
        await updateUserAPI(userForm.value)
        ElMessage.success('修改成功')
    } else {
        await addAclUserAPI(userForm.value)
        ElMessage.success('新增成功')
    }
    drawer.value = false
    getAclUserData()
    form.value.resetFields()
}
//批量删除
const selectIdArr=ref<records>([])
const changeSection = (values: any) => {
    selectIdArr.value = values
    

}
const deleteAll = async () => {
    const idList=selectIdArr.value.map(item=>(item.id as number))    
    await delAllUserAPI(idList)
    if(userList.value.length > 1){
        ElMessage.success('删除成功')
        getAclUserData()
    }else{
        page.value - 1
        ElMessage.success('删除成功')
        getAclUserData()
    }
   
}

// 角色抽屉
const allRole=ref<AllRole>([])
const userRole=ref<AllRole>([])
const setRole=async(row:any)=>{
    Object.assign(userForm.value,row)
    const res:AllRoleRes=await getRoleAPI(userForm.value.id as number)
    allRole.value=res.data.allRolesList
    userRole.value=res.data.assignRoles
    roleDrawer.value=true
}
// 全选
const checkAll=ref(false)
const isIndeterminate=ref(true)
const handelselectAll=(value:boolean)=>{
    userRole.value=value? allRole.value :[]
    isIndeterminate.value=false
}
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === allRole.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < allRole.value.length
}

//取消按钮
const cancalClick=()=>{
    roleDrawer.value=false
}
//确认按钮
const confirmClick=async()=>{
    const data:setRoleParmas={
        userId:(userForm.value.id as number),
        roleIdList:userRole.value.map(item=>(item.id as number))
    }
    await setRoleAPI(data)
    ElMessage.success('分配角色成功')
    roleDrawer.value=false
    getAclUserData()
}
</script>

<template>
    <!-- 头部 -->
    <el-card style="height: 80px;">
        <el-form :inline="true" class="form">
            <el-form-item label="用户名:">
                <el-input placeholder="请输入搜索用户名" v-model="keyword"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :disabled="keyword ?false :true" @click="search">搜索</el-button>
                <el-button type="primary" plain @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <!-- 主体 -->
    <el-card style="margin: 10px 0px;">
        <!-- 按钮 -->
        <el-button type="primary" @click="addUser">添加</el-button>
        <el-button type="danger" plain :disabled="selectIdArr.length ? false : true" @click="deleteAll">批量删除</el-button>
        <!-- 表格 -->
        <el-table border style="margin: 10px 0px;" :data="userList" @selection-change="changeSection">
            <el-table-column type="selection" width="50px" align="center"></el-table-column>
            <el-table-column type="index" label="#" align="center"></el-table-column>
            <el-table-column prop="id" label="ID" align="center"></el-table-column>
            <el-table-column prop="username" label="用户名字" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="name" label="用户名称" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="roleName" label="用户角色" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="updateTime" label="更新时间" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" width="300px" align="center">
                <template #="{ row }">
                    <el-button type="primary" icon="User" style="width: 100px;" size="small" @click="setRole(row)">分配角色</el-button>
                    <el-button type="primary" icon="Edit" size="small" @click="updateUser(row)">编辑</el-button>
                    <el-popconfirm :title="`你确认要删除${userForm.username}吗?`" confirm-button-text="确认"
                        cancel-button-text="取消" @confirm="onConfirm(row.id)" width="260px">
                        <template #reference>
                            <el-button type="primary" icon="Delete" size="small">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-pagination v-model:current-page="page" v-model:page-size="limit" :page-sizes="[1, 3, 5, 10]"
            :background="true" layout="prev, pager, next, jumper,->, sizes,total" :total="total"
            @current-change="changeCurrent" @size-change="changePageSize" />
        <!-- 用户抽屉 -->
        <el-drawer v-model="drawer" :title="userForm.id ? '编辑用户' : '添加用户'">
            <el-form ref="form" :model="userForm" :rules="rules">
                <!-- 表单 -->
                <el-form-item label="用户姓名" prop="username">
                    <el-input placeholder="请输入用户姓名" v-model="userForm.username"></el-input>
                </el-form-item>
                <el-form-item label="用户昵称" prop="name">
                    <el-input placeholder="请输入用户昵称" v-model="userForm.name"></el-input>
                </el-form-item>
                <el-form-item label="用户密码" prop="password" v-if="!userForm.id">
                    <el-input placeholder="请输入用户密码" v-model="userForm.password"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div style="flex: auto">
                    <el-button @click="cancel">取消</el-button>
                    <el-button type="primary" @click="confirm">确认</el-button>
                </div>
            </template>
        </el-drawer>
        <!-- 角色抽屉 -->
         <el-drawer title="分配角色(职位)" v-model="roleDrawer">
                <el-form ref="form" :model="form" label-width="80px">
                 <el-form-item label="用户姓名">
                    <el-input v-model="userForm.username" disabled></el-input>
                 </el-form-item>
                 <el-form-item label="职位列表">
                    <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handelselectAll">全选</el-checkbox>
                    <!-- 显示职位的复选框 -->
                     <el-checkbox-group v-model="userRole"  @change="handleCheckedCitiesChange">
                         <el-checkbox v-for="(role,index) in allRole" :key="index" :label="role">{{ role.roleName }}</el-checkbox>
                     </el-checkbox-group>
                 </el-form-item>
             </el-form>
             <template #footer>
                <div style="flex: auto;">
                    <el-button @click="cancalClick">取消</el-button>
                    <el-button type="primary" @click="confirmClick">确认</el-button>
                </div>
             </template>
         </el-drawer>
    </el-card>
</template>

<style scoped lang="scss">
.form {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>